package com.yjd.comm.fs.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;


public class FtpUtil {
	private Logger logger = Logger.getLogger(FtpUtil.class);

	/**
	 * FTP客户端
	 */
	private FTPClient ftpClient;

	/**
	 * FTP服务器IP
	 */
	private String ip;

	/**
	 * FTP服务器PORT
	 */
	private int port;

	/**
	 * FTP服务器用户
	 */
	private String user;

	/**
	 * FTP服务器用户密码
	 */
	private String password;

	public FtpUtil(String ip, int port, String user, String password) {
		this.ip = ip;
		this.port = port;
		this.user = user;
		this.password = password;
	}

	/**
	 * 服务器连接
	 * 
	 * @param ip
	 *            服务器IP
	 * @param port
	 *            服务器端口
	 * @param user
	 *            用户名
	 * @param password
	 *            密码
	 * @param path
	 *            服务器路径
	 */
	public void connectServer() {
		try {
			/* ******连接服务器的两种方法****** */
			ftpClient = new FTPClient();
			ftpClient.connect(ip, port);
			ftpClient.login(this.user, this.password);
			ftpClient.setControlEncoding("GBK");
			// 设置成2进制传输
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			// ftpClient.configure(getFtpConfig());

			int reply = ftpClient.getReplyCode();
			ftpClient.setDataTimeout(120000);

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				logger.debug("FTP server refused connection.");
				// logger.debug("FTP 服务拒绝连接！");
			}
			logger.debug("FTP登入成功login success!");

		} catch (IOException ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}

	/**
	 * 设置FTP客服端的配置--一般可以不设置
	 * 
	 * @return ftpConfig
	 */
	@SuppressWarnings("unused")
	private FTPClientConfig getFtpConfig() {
		FTPClientConfig ftpConfig = new FTPClientConfig(
				FTPClientConfig.SYST_UNIX);
		ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
		return ftpConfig;
	}

	/**
	 * 关闭连接
	 */
	public void closeConnect() {
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
				logger.debug("FTP登入退出成功loginout success!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传单个文件，并重命名
	 * 
	 * @param localFile
	 *            --本地文件路径
	 * @param distFolder
	 *            --新的文件名,可以命名为空""
	 * @return true 上传成功，false 上传失败
	 */
	public boolean upload(String localFileStr, String remotefile) {
		logger.debug("                    -------------------------");
		boolean flag = true;
		try {

			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

			String charsetName = "GBK";
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
					"OPTS UTF8", "ON"))) // 发送OPTS UTF8指令，尝试支持utf-8
				charsetName = "utf-8";
			remotefile = new String(remotefile.getBytes(charsetName),
					"ISO-8859-1");

			File localFile = new File(localFileStr);
			InputStream input = new FileInputStream(localFile);

			
			CreateDirecroty(remotefile);
			flag = ftpClient.storeFile(remotefile, input);
			if (flag) {
				logger.debug("上传文件成功！");
			} else {
				logger.debug("上传文件失败！");
			}
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
			logger.debug("本地文件上传失败！");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	
	/** *//**   
     * 递归创建远程服务器目录   
     * @param remote 远程服务器文件绝对路径   
     * @param ftpClient FTPClient对象   
     * @return 目录创建是否成功   
     * @throws IOException   
     */    
    public boolean CreateDirecroty(String remote) throws IOException{      
        String directory = remote.substring(0,remote.lastIndexOf("/")+1);      
        if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){      
            //如果远程目录不存在，则递归创建远程服务器目录      
            int start=0;      
            int end = 0;      
            if(directory.startsWith("/")){      
                start = 1;      
            }else{      
                start = 0;      
            }      
            end = directory.indexOf("/",start);      
            while(true){      
                String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");      
                if(!ftpClient.changeWorkingDirectory(subDirectory)){      
                    if(ftpClient.makeDirectory(subDirectory)){      
                        ftpClient.changeWorkingDirectory(subDirectory);      
                    }else {      
                        logger.debug("创建目录失败");      
                        return false;      
                    }      
                }      
                      
                start = end + 1;      
                end = directory.indexOf("/",start);      
                      
                //检查所有目录是否创建完毕      
                if(end <= start){      
                    break;      
                }      
            }      
        }      
        return true;      
    }   

	/**
	 * 下载文件
	 * 
	 * @param remoteFileName
	 *            --服务器上的文件名
	 * @param localFileName
	 *            --本地文件名
	 * @return true 下载成功，false 下载失败
	 */
	public boolean download(String remoteFileName, String localFileName) {
		boolean flag = true;
		// 下载文件
		BufferedOutputStream buffOut = null;
		try {

			String charsetName = "GBK";
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
					"OPTS UTF8", "ON"))) // 发送OPTS UTF8指令，尝试支持utf-8
				charsetName = "utf-8";
			remoteFileName = new String(remoteFileName.getBytes(charsetName),
					"ISO-8859-1");

			File file_in = new File(localFileName);
			if (file_in.exists()) {
				file_in.delete();
			}

			File dir = new File(file_in.getParent());
			if (!dir.exists()) {
				dir.mkdir();
			}

			buffOut = new BufferedOutputStream(new FileOutputStream(
					localFileName));
			flag = ftpClient.retrieveFile(remoteFileName, buffOut);
			if (flag) {
				logger.debug("本地文件下载成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("本地文件下载失败");
		} finally {
			try {
				if (buffOut != null)
					buffOut.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return flag;
	}

	public InputStream downloadForPHP(String remoteFileName) {
		try {
			String charsetName = "GBK";
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
					"OPTS UTF8", "ON"))) // 发送OPTS UTF8指令，尝试支持utf-8
				charsetName = "utf-8";
			remoteFileName = new String(remoteFileName.getBytes(charsetName),
					"ISO-8859-1");

			return ftpClient.retrieveFileStream(remoteFileName);
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("本地文件下载失败");
		}
		return null;

	}

	/**
	 * 删除一个文件
	 */
	public boolean deleteFile(String filename) {
		boolean flag = true;
		try {

			flag = ftpClient.deleteFile(filename);
			if (flag) {
				logger.debug("删除文件成功！");
			} else {
				logger.debug("删除文件失败！");
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return flag;
	}

	/**
	 * 删除目录
	 */
	public void deleteDirectory(String pathname) {
		try {

			File file = new File(pathname);
			if (file.isDirectory()) {
				File file2[] = file.listFiles();
			} else {
				deleteFile(pathname);
			}
			ftpClient.removeDirectory(pathname);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 删除空目录
	 */
	public void deleteEmptyDirectory(String pathname) {
		try {

			ftpClient.removeDirectory(pathname);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 列出服务器上文件和目录
	 * 
	 * @param regStr
	 *            --匹配的正则表达式
	 */
	public void listRemoteFiles(String regStr) {

		try {
			String files[] = ftpClient.listNames(regStr);
			if (files == null || files.length == 0)
				logger.debug("没有任何文件!");
			else {
				for (int i = 0; i < files.length; i++) {
					logger.debug(files[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 列出Ftp服务器上的所有文件和目录
	 */
	public void listRemoteAllFiles() {

		try {
			String[] names = ftpClient.listNames();
			for (int i = 0; i < names.length; i++) {
				logger.debug(names[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 返回根目录
	 */
	public void backRoot() {
		try {
			ftpClient.changeWorkingDirectory("\\");
		} catch (IOException e) {
			logger.debug("返回根目录出错");
			e.printStackTrace();
		}

	}

	/**
	 * 设置传输文件的类型[文本文件或者二进制文件]
	 * 
	 * @param fileType
	 *            --BINARY_FILE_TYPE、ASCII_FILE_TYPE
	 * 
	 */
	public void setFileType(int fileType) {
		try {

			ftpClient.setFileType(fileType);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 扩展使用
	 * 
	 * @return ftpClient
	 */
	protected FTPClient getFtpClient() {

		return ftpClient;
	}

	public static void main(String agrs[]) {

		String filepath[] = { "/ftp1/hxx_admin_logs管理员登入日志.sql",
				"/ftp1/mfq_check_type审核类型.sql" };
		String localfilepath[] = { "D:\\管理员登入日志.sql", "D:\\审核类型.sql" };

		FtpUtil fu = new FtpUtil("192.168.10.248", 21, "lindy", "lin715674040");
		/*
		 * 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
		 */
		fu.connectServer();
		// 下载
		// for (int i = 0; i < filepath.length; i++) {
		// fu.download(filepath[i], localfilepath[i]);
		// }

		String localfile = "D:\\管理员登入日志.sql";
		String remotefile = "/ddddffff/gggggggg/登入日登入日登入日登入日登入日2.sql";
		// 上传
		fu.upload(localfile, remotefile);
		
//		long time=FrameUtil.getTime(null);
//		logger.debug(time);
//		fu.upload("D:\\ftptestFile\\Tulips.jpg", "/2013/12/26/1135413811699601765668.jpg");
////		/user/19/2/181534/1132585958427080417170.jpg
//		// 2013/12/26/1135413811699601765668.jpg
//		long time2=FrameUtil.getTime(null);
//		logger.debug(time2);
		fu.connectServer();
	}
}